import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { Card, Typography, Tag, Spin, Alert, Button, Space, Checkbox, message } from 'antd';
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons';

// 导入action
import {
  fetchCommentDetail,
  updateCommentTags,
  clearCommentDetail,
  selectCommentDetail,
  selectCommentLoading,
  selectCommentError
} from './commentSlice';

// 导入API和类型
import { getCommentTags } from '@/api/commentApi';
import { Comment, CommentTag } from '@/types/comment';
import { RootState } from '@/store';

const { Title, Paragraph, Text } = Typography;

const CommentDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const dispatch = useDispatch();
  const navigate = useNavigate();

  // 从Redux获取状态
  const currentComment = useSelector(selectCommentDetail);
  const loading = useSelector(selectCommentLoading);
  const error = useSelector(selectCommentError);
  const tagsLoading = useSelector((state: RootState) => state.comments.tagsLoading);

  // 本地状态
  const [allTags, setAllTags] = useState<CommentTag[]>([]);
  const [selectedTagIds, setSelectedTagIds] = useState<string[]>([]);
  const [isEditing, setIsEditing] = useState(false);

  // 加载评论详情
  useEffect(() => {
    if (!id) return;

    dispatch(fetchCommentDetail(id) as any)
  .unwrap()
  .then((comment: Comment) => {
    setSelectedTagIds(comment.tagIds || []);
  });

    // 加载所有可用标签
    const loadTags = async () => {
      try {
        const data = await getCommentTags();
        setAllTags(data.tags);
      } catch (err) {
        message.error('加载标签失败');
      }
    };

    loadTags();

    // 组件卸载时清理状态
    return () => {
      dispatch(clearCommentDetail());
    };
  }, [id, dispatch]);

  // 处理标签选择变化
  const handleTagChange = (tagId: string, checked: boolean) => {
    if (checked) {
      setSelectedTagIds(prev => [...prev, tagId]);
    } else {
      setSelectedTagIds(prev => prev.filter(id => id !== tagId));
    }
  };

  // 保存标签修改
  const handleSaveTags = async () => {
    if (!id) return;

    try {
      await (dispatch(updateCommentTags({ id, tagIds: selectedTagIds }) as any).unwrap());
      message.success('标签更新成功');
      setIsEditing(false);
    } catch (err) {
      message.error('标签更新失败');
    }
  };

  if (loading) {
    return <Spin size="large" style={{ display: 'block', margin: '50px auto' }} />;
  }

  if (error) {
    return <Alert message="错误" description={error} type="error" showIcon />;
  }

  if (!currentComment) {
    return <Alert message="提示" description="未找到评论信息" type="info" showIcon />;
  }

  return (
    <div className="comment-detail-page">
      <Button
        icon={<ArrowLeftOutlined />}
        onClick={() => navigate('/comments')}
        style={{ marginBottom: 16 }}
      >
        返回列表
      </Button>

      <Card title="评论详情" bordered={true}>
        <Typography>
          <Title level={4}>产品：{currentComment.productName}</Title>

          <Paragraph style={{ margin: '20px 0' }}>
            {currentComment.content}
          </Paragraph>

          <Space size="middle" style={{ display: 'block', marginBottom: 16 }}>
            <Text strong>用户：</Text>
            <Text>{currentComment.username}</Text>
          </Space>

          <Space size="middle" style={{ display: 'block', marginBottom: 16 }}>
            <Text strong>发布时间：</Text>
            <Text>{currentComment.createdAt}</Text>
          </Space>

          <Space size="middle" style={{ display: 'block', marginBottom: 16 }}>
            <Text strong>情感倾向：</Text>
            <Tag color={
              currentComment.sentiment === 'positive' ? 'green' :
              currentComment.sentiment === 'negative' ? 'red' : 'gray'
            }>
              {currentComment.sentiment === 'positive' ? '正面' :
               currentComment.sentiment === 'negative' ? '负面' : '中性'}
            </Tag>
          </Space>

          <div style={{ margin: '20px 0' }}>
            <Title level={5} style={{ marginBottom: 16 }}>评论标签</Title>

            {isEditing ? (
              <div>
                <div style={{ marginBottom: 16 }}>
                  {allTags.map(tag => (
                    <Checkbox
                      key={tag.id}
                      checked={selectedTagIds.includes(tag.id)}
                      onChange={(e) => handleTagChange(tag.id, e.target.checked)}
                      style={{ marginRight: 12, marginBottom: 8 }}
                    >
                      <Tag color={tag.color}>{tag.name}</Tag>
                    </Checkbox>
                  ))}
                </div>

                <Space>
                  <Button
                    type="primary"
                    icon={<SaveOutlined />}
                    onClick={handleSaveTags}
                    loading={tagsLoading}
                  >
                    保存
                  </Button>
                  <Button onClick={() => setIsEditing(false)}>取消</Button>
                </Space>
              </div>
            ) : (
              <div>
                <Space size="small" wrap>
                  {currentComment.tags.map((tag: CommentTag) => (
                    <Tag key={tag.id} color={tag.color}>{tag.name}</Tag>
                  ))}
                </Space>
                <Button
                  style={{ marginLeft: 12 }}
                  onClick={() => setIsEditing(true)}
                >
                  编辑标签
                </Button>
              </div>
            )}
          </div>

          {currentComment.predictionResult && (
            <div style={{ marginTop: 20 }}>
              <Title level={5}>AI预测结果</Title>
              <Text strong>模型：</Text>
              <Text>{currentComment.predictionResult.modelId}</Text>
              <br />
              <Text strong>置信度：</Text>
              <Text>{(currentComment.predictionResult.confidence * 100).toFixed(2)}%</Text>
              <br />
              <Text strong>预测时间：</Text>
              <Text>{currentComment.predictionResult.predictedAt}</Text>
            </div>
          )}
        </Typography>
      </Card>
    </div>
  );
};

export default CommentDetailPage;
    